<?php
class languages extends CWidget
{
	public function init()
	{
		parent::init();
	}
	public function run()
	{
		$curr_language  = Yii::app()->language;
		$Languages = Yii::app()->params['languages'];
		$langs = array();
		foreach($Languages as $key => $value){
			$langs[$key] = array('name'=>$value,
								 'url' =>$this->GetRounterUrlLang($key)
								);
		}
		$this->render('default', array('curr_language'=>$curr_language, 'lang_url'	=>	$langs));
	}
	private function GetRounterUrlLang($lang)
	{
		if($lang==$_GET['lang']){
			return '#';
		}
		
		$controller = Yii::app()->controller->getId();
		$action = Yii::app()->controller->getAction()->getId();
		$module = (Yii::app()->controller->getModule()!==null)?Yii::app()->controller->getModule()->getId():"";
		$params = '';
		$route = $controller.'/'.$action;
		$UrlParams = $_GET;
		switch ($route)
		{
			case 'post/read':
				$surfix = ($lang==Yii::app()->params['language_default'])?"":"_".$lang;
				$alias_attr  = (Yii::app()->language!=Yii::app()->params['language_default'])?"alias_".Yii::app()->language:"alias";
				$sql = "SELECT *
						FROM tbl_content
						WHERE $alias_attr=:alias AND type='post' AND status = ".FNews::STATUS_PUBLISHED;
				$command = Yii::app()->db->createCommand($sql);
				$command->bindParam(':alias', $_GET['alias']);
				$data = $command->queryRow();
				$UrlParams['alias'] = $data['alias'.$surfix];
				$sql = "SELECT alias, alias_en
						FROM tbl_categories
						WHERE $alias_attr=:alias AND published = 1";
				$command = Yii::app()->db->createCommand($sql);
				$command->bindParam(':alias', $_GET['cat_alias']);
				$category = $command->queryRow();
				$UrlParams['cat_alias'] = $category['alias'.$surfix];
				break;
			case 'site/page':
				$surfix = ($lang==Yii::app()->params['language_default'])?"":"_".$lang;
				$alias_attr  = (Yii::app()->language!=Yii::app()->params['language_default'])?"alias_".Yii::app()->language:"alias";
				$sql = "SELECT alias, alias_en
						FROM tbl_content
						WHERE type='page' AND $alias_attr=:alias AND status = ".FNews::STATUS_PUBLISHED;
				$command = Yii::app()->db->createCommand($sql);
				$command->bindParam(':alias', $_GET['alias']);
				$page = $command->queryRow();
				$alias = 'alias'.$surfix;
				$UrlParams['alias'] = $page["$alias"];
				break;
			default:
				break;
		}
		
		if(key_exists('lang', $UrlParams)==false && $lang!=Yii::app()->params['language_default']){
			$UrlParams['lang'] = $lang;
			}else{
				if($lang==Yii::app()->params['language_default']){
					unset($UrlParams['lang']);
				}else{
					$UrlParams['lang'] = $lang;
				}
			}
		
		$UrlParams['lang'] = $lang;
		$r = $module.'/'.$controller.'/'.$action;
		return  Yii::app()->createUrl("$r", $UrlParams);
	}
}